package com.emellend.api11.nfc;

import com.emellend.api11.R;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.nfc.NfcAdapter;
import android.nfc.tech.NfcF;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class ForegroundDispatch extends Activity {
	private TextView mText;
	private NfcAdapter mAdapter;
	private PendingIntent mPendingIntent;
	private IntentFilter[] mFilters;
	private String[][] mTechLists;
	private int mCount = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.foreground_dispatch);
		mText = (TextView) findViewById(R.id.text);
	    mText.setText("Scan a tag");
	    
	    mAdapter = NfcAdapter.getDefaultAdapter();
	    mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
	    IntentFilter ndef=new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
	    
	    try {
			ndef.addDataType("*/*");
		} catch (MalformedMimeTypeException e) {
			e.printStackTrace();
		}
	    
	    mFilters = new IntentFilter[]{ndef};
	    mTechLists = new String[][]{new String[]{NfcF.class.getName()}};
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists);
	}
	
	@Override
	protected void onNewIntent(Intent intent) {
		Log.i("Foreground dispatch", "Discovered tag with intent: " + intent);
        mText.setText("Discovered tag " + ++mCount + " with intent: " + intent);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		 mAdapter.disableForegroundDispatch(this);
	}
}
